<?php

namespace App\Http\Controllers\Api\Mobile;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Carbon\Carbon;

use App\Models\VideoCategory;
use App\Models\Tag;
use App\Models\Order;
use App\Models\Video;
use App\Models\OutVideo;
use App\Models\Domain;
use App\Models\CdnDomain;
use Illuminate\Support\Facades\DB;

use App\Services\CdnService;
use App\Jobs\ImportFromPpvod;

class VideoController extends Controller
{
    protected $cdn_service;

    public function __construct(CdnService $cdn_service){
        $this->cdn_service = $cdn_service;
    }

    /**
     * 视频加载
     *
     * @param Request $request
     * @return void
     */
    public function index(Request $request){
        if($request->has('code') && $request->code){
            $code_data = decodeCode($request->code);
            //参数判断，解析后的code是数组
            if(is_array($code_data) && count($code_data)>3){ 
                $limit = $request->limit??22;
                $page = $request->page??1;
                $offset = $limit*($page-1);
                // 创建一个查询构造器
                $builder = null;
                //标签查找视频
                if($request->tag_id){
                    $builder = Tag::find($request->tag_id)->videos()->distinct();
                }else{
                    $builder = Video::query()->show();
                }
                //指定分类
                if($category_id = $request->category_id){
                    $builder->where('category_id', $category_id);
                }
                //搜索关键词
                if ($search_str =  $request->search) {
                    //缓存视频库
                    $titles = cache()->remember('videos_titles', 86400,function ()use($code_data){
                        $videos = Video::show()->select(['id','title'])->get();
                        if(count($videos)){
                            return $videos->toArray();
                        }
                        return [];
                    });
                    $ids = [];
                    //获取匹配的id
                    if(count($titles)){
                        foreach($titles as $item){
                            if (strstr( $item['title'] , $search_str ) !== false ){
                                $ids[] = $item['id'];
                            }
                        }
                    }
                    $builder->whereIn('id',$ids);
                }
                //推荐视频
                if ($recommend = $request->recommend) {
                    $builder->where('is_recommend', $recommend);
                }
                //是否已支付
                if($paid = $request->buyed){
                    $openid = $code_data[2];
                    $ids =  Order::paid()->where('openid',$openid)->where('paid_at','>',Carbon::now()->addDays(-1))->pluck('video_id');
                    $builder->whereIn('id',$ids);
                }
                //热播视频排序
                if($selltop = $request->selltop){
                    // $ids = Order::select(DB::raw('count(*) as count,video_id')->groupBy('video_id')->orderBy('count','desc')->get()->toArray();
                    $ids = Order::groupBy('video_id')->pluck('video_id');
                    $builder->whereIn('id',$ids);

                }
                if($request->random_view){
                    //随机加载(随便看看)
                    $builder->inRandomOrder();
                }else{
                    $builder->orderBy('updated_at','desc');
                }
                
                //触底加载
                if($request->distinct && $page!=1){
                    if($ids = cache('loaded_videos:'.$code_data[2])){
                        $builder->whereNotIn('id',$ids);
                    }
                }else{
                    //切换了分类，不是首次加载后的触底
                    cache()->forget('loaded_videos:'.$code_data[2]);
                }
                $builder->limit($limit)->with('category');
                $pic_type= $request->pic_type??'db_base64';
                // 获取视频列表,shuffle数组乱序
                if($pic_type=='db_base64'){
                    $data['videos'] = $builder->get()->makeHidden(['title','category_id','state','is_recommend']);
                }else if($pic_type=='encode_img'){
                    //图片cdn
                    $img_cdns = $this->cdn_service->getImgCdn();
                    if($img_cdns['state']!='success' || ($img_cdns['img_cdn1']=='' && $img_cdns['img_cdn2']=='')){
                        return errorGo($img_cdns['state']);
                    }
                    $data['img_cdns'] = $img_cdns;
                    $data['videos'] = $builder->get()->makeHidden(['base64','title','category_id','state','is_recommend']);
                }else{
                    $data['videos'] = $builder->get()->makeHidden(['base64','title','category_id','state','is_recommend']);
                    //图片服务器域名
                    $data['img_domain'] = cache()->rememberForever('img_domain',  function () {
                        //加锁防止没有时缓存穿透
                        return Cache::lock('img_domain')->get(function () {
                            // 获取无限期锁并自动释放...
                            return CdnDomain::show()->where('type',3)->value('domain');
                        });
                    });
                }
                
                //此次加载的id
                $ids = [];
                $videoarray = [];
                foreach($data['videos'] as $item){
                    $ids[] = $item->id;
                    $item->_category = $item->category->c_name;
                    unset($item->category);
                    $videoarray[] = $item->toarray();
                }
                $data['videos']=$videoarray;
                if($_ids = cache('loaded_videos:'.$code_data[2])){
                    $ids = array_merge($ids,$_ids);
                }
                cache()->put('loaded_videos:'.$code_data[2], $ids,600);
                
                // $data=cryptoJsAesEncrypt(json_encode($data));
                return $this->success($data);
            }
            else{
                return $this->errMsg('有情况，请通过正常渠道访问！');
            }
        }
        return $this->errMsg('有情况，请通过正常渠道访问');
    }


    /**
     * 视频分类
     *
     * @param Request $request
     * @return void
     */
    public function categories(Request $request){
        //视频分类
        $data['categories'] = Cache::rememberForever('categories',  function () {
            return VideoCategory::show()->select('id','name')->get()->toArray();
        });
        return $this->success($data);
    }

    
    /**
     * 视频标签
     *
     * @param Request $request
     * @return void
     */
    public function tags(Request $request){
        //视频标签
        $data['tags'] = Cache::rememberForever('tags',  function () {
            return Tag::show()->select('id','name')->get()->toArray();
        });
        return $this->success($data);
    }
    /**
     * 视频标签评价
     *
     * @param Request $request
     * @return void
     */
    public function tagToVideo(Request $request){
        $tag_id = $request->tag_id;
        $video_id = $request->video_id;
        $video =Video::find($video_id);

        $video->tags()->attach($tag_id);
        return $this->success('已提交');
    }

    /**
     * ppvod 视频同步导入
     */
    public function ppvodImport(Request $request){
        $token = config('ppvod.ppvod_import_token');
        $inputs = $request->all();

        if($token != $inputs['token']){
            return;
        }
        ImportFromPpvod::dispatch($inputs);
    }
}
